package ym.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import ym.mapper.AnnouncementMapper;
import ym.pojo.Announcement;
import ym.service.AnnouncementService;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import static com.baomidou.mybatisplus.extension.toolkit.Db.saveBatch;

@Service
public class AnnouncementServiceImpl implements AnnouncementService {
    @Autowired
    private AnnouncementMapper announcementMapper;


    @Override
    public void add(Announcement announcement) {
        announcementMapper.insert(announcement);
    }

    @Override
    public void update(Announcement announcement) {
        announcementMapper.updateById(announcement);
    }

    @Override
    public void delete(Integer id) {
        announcementMapper.deleteById(id);
    }

    @Override
    public Announcement findById(Integer id) {
        return announcementMapper.selectById(id);
    }

    @Override
    public List<Announcement> findAll() {
        return announcementMapper.selectList(null);
    }

    @Override
    public Page<Announcement> search(String search, int page, int size) {
        QueryWrapper<Announcement> queryWrapper = new QueryWrapper<>();
        if (search != null) {
//            queryWrapper.like("", search);
        }
        return announcementMapper.selectPage(new Page(page, size), queryWrapper);
    }

    @Override
    public void exportExcel(HttpServletResponse response) throws IOException {
        //需要导出的数据列表
        List<Announcement> announcementList = announcementMapper.selectList(null);
        //创建sheet
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("公告数据");
        //创建表头
        Row headerRow = sheet.createRow(0);
        String[] headers = {"ID", "标题", "简介", "内容", "发布时间"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }
        //填充数据到sheet
        for (int i = 0; i < announcementList.size(); i++) {
            Announcement announcement = announcementList.get(i);
            Row row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(announcement.getAnnouncementId());//id
            row.createCell(1).setCellValue(announcement.getAnnouncementTitle());//标题
            row.createCell(2).setCellValue(announcement.getAnnouncementDesc());//简介
            row.createCell(3).setCellValue(announcement.getAnnouncementContent());//内容
            row.createCell(4).setCellValue(announcement.getAnnouncementTime());//发布时间
        }
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("公告数据.xlsx", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        // 输出文件
        try (OutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
        }
    }

    @Override
    public boolean importExcel(MultipartFile file) throws IOException {
        //读取Excel文件
        try (InputStream inputStream = file.getInputStream();
             //根据文件类型创建对应的Workbook对象
             Workbook workbook = new XSSFWorkbook(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0);
            //创建一个集合，用于存储从Excel中读取的数据
            List<Announcement> announcementList = new ArrayList<>();
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                //导出时不要id
                Announcement announcement = new Announcement();
                announcement.setAnnouncementTitle(getCellValueAsString(row.getCell(1)));//标题
                announcement.setAnnouncementDesc(getCellValueAsString(row.getCell(2)));//简介
                announcement.setAnnouncementContent(getCellValueAsString(row.getCell(3)));//内容
                announcement.setAnnouncementTime(getCellValueAsString(row.getCell(4)));//时间
                announcementList.add(announcement);
            }
            //全部添加到数据库中
            return saveBatch(announcementList);
        }
    }




    /**
     * 将Excel单元格内容转换为字符串
     *
     * @param cell Excel单元格对象
     * @return 转换后的字符串，如果单元格为空则返回空字符串
     */
    private String getCellValueAsString(Cell cell) {
        if (cell == null) {  // 检查单元格是否为空
            return "";       // 如果为空，返回空字符串
        }
        switch (cell.getCellType()) {  // 根据单元格类型进行判断
            case STRING:  // 如果是字符串类型
                return cell.getStringCellValue();  // 直接返回字符串值
            case NUMERIC:  // 如果是数字类型
                if (DateUtil.isCellDateFormatted(cell)) {  // 检查是否是日期格式
                    return cell.getDateCellValue().toString();  // 返回日期字符串
                } else {  // 如果是普通数字
                    return String.valueOf((int) cell.getNumericCellValue());  // 将数字转为整数后返回
                }
            case BOOLEAN:  // 如果是布尔类型
                return String.valueOf(cell.getBooleanCellValue());  // 返回布尔值的字符串形式
            default:  // 其他类型
                return "";  // 返回空字符串
        }
    }
}
